package shark.oss.impl;

import shark.oss.OssFileService;
import shark.oss.exception.OssException;
import shark.oss.model.FileUrl;
import shark.oss.model.ServerDefine;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class OssFileServiceImpl implements OssFileService {
    private static final String FILE_URL_PATTERN = "^[^\\\\/:*?\"<>|\r\n]+?:[^\\\\/:*?\"<>|\r\n]+(/{1}[^\\\\/:*?\"<>|\r\n]+)*$";

    private String serverName;
    private String serverType;

    public OssFileServiceImpl(ServerDefine serverDefine) {
        this.serverName = serverDefine.getName();
        this.serverType = serverDefine.getType();
    }

    public String getServerName() {
        return serverName;
    }

    public String getServerType() {
        return serverType;
    }

    protected FileUrl parseFileUrl(String fileUrl) throws OssException {
        Pattern serverRegex = Pattern.compile("^[^\\\\/:*?\"<>|\r\n]+?:");
        Pattern fileRegex = Pattern.compile("[/:]([^\\\\/:*?\"<>|\r\n]+)$");

        int index1 = 0;
        int index2 = 0;

        if(fileUrl!=null && fileUrl.matches(FILE_URL_PATTERN)){
            Matcher regexMatcher = serverRegex.matcher(fileUrl);
            if (regexMatcher.find()) {
                index1 = regexMatcher.end();
            }

            regexMatcher = fileRegex.matcher(fileUrl);
            if (regexMatcher.find()) {
                index2 = regexMatcher.start(1);
            }

            if(index1 == 0 || index2 == 0 || index1 > index2){
                throw new OssException("附件url格式错误，fileUrl = " + (fileUrl == null ? "null" : fileUrl));
            }

            return new FileUrl(
                    fileUrl.substring(0, index1-1),
                    fileUrl.substring(index1 , index2 ),
                    fileUrl.substring(index2));
        } else {
            throw new OssException("附件url格式错误，fileUrl = " + (fileUrl == null ? "null" : fileUrl));
        }
    }

    protected String generateFileUrl(String serverName,String path,String fileId) throws OssException{
        if(serverName == null || serverName.isEmpty()){
            throw new OssException("创建附件服务器自定义格式的FileUrl地址时附件服务器名为null");
        }
        if(path == null || path.isEmpty()){
            throw new OssException("创建附件服务器自定义格式的FileUrl地址时附件路径为null");
        }
        if(fileId == null || fileId.isEmpty()){
            throw new OssException("创建附件服务器自定义格式的FileUrl地址时附件名称(ID)为null");
        }

        StringBuilder result = new StringBuilder();
        result.append(serverName);
        result.append(":");
        result.append(path);
        if(!path.endsWith("/")){
            result.append("/");
        }
        result.append(fileId);

        return result.toString();
    }

    protected void download(InputStream instream, String fileName,
                            HttpServletRequest request, HttpServletResponse response)
            throws OssException{

        OutputStream outStream = null;
        try{
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");

            byte[] buffer = new byte[1024];
            int size;
            outStream = response.getOutputStream();
            do{
                size = instream.read(buffer,0,1024);
                if(size>0){
                    outStream.write(buffer,0,size);
                }
            }while(size>0);
        } catch (Exception ex) {
            throw new OssException("下载数据失败",ex);
        }finally {
            if(outStream!=null){
                try {
                    outStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
